﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HslCommunication;
using Net_SCADA.Forms;

namespace Net_SCADA
{
    public partial class Form_ProcessBox : fdBaseForm
    {
        ProcessBox pbox;
        Size btnSize = new Size(150, 50);
        private Font[] keyTimeNameFont = new Font[] { new Font("Microsoft YaHei", 12f), new Font("Arial", 12f) };
        public Form_ProcessBox(ProcessBox box)
        {
            InitializeComponent();

            this.StartPosition = FormStartPosition.CenterScreen;//将Form显示在屏幕中间
            pbox = box;//把获取的box值赋给pb
        }
        private void Form_ProcessBox_Load(object sender, EventArgs e)
        {
            LoadBoxKeyTime();//加载工位信息中ListView的各个数据
            loadCmb();//加载工位信息修改中ComboBox数据
            LoadBox();//加载工位信息相关内容（KeytimeIndex、KeytimeOutIndex、errorcode、boxserial、boxmark等数据）
            //ProcessBoxStatus();//根据工位状态，显示或隐藏
            //LoadCuttedProcessBox();//加载被剪切的工位信息数据
            //netForms.fmpbox = this;
        }
        public void loadCmb()
        {
            for (int i = 0; i < fdPublicFunction.boxColorSet.Length; i++) {
                cmb_ColorSet.Items.Add(fdPublicFunction.boxColorSet[i].colorName[formLanguageIndex]);
            }
            if (pbox.LampCode < fdPublicFunction.boxColorSet.Length)
                cmb_ColorSet.SelectedIndex = pbox.LampCode;
            else
                cmb_ColorSet.SelectedIndex = 0;
        }
        private void LoadBoxKeyTime()
        {
            grdTimeList.Rows.Add(NetLine.BoxKeyTime.Count);
            for (int i = 0; i < NetLine.BoxKeyTime.Count; i++)
            {
                grdTimeList.Rows[i].SetValues(i + 1, NetLine.BoxKeyTime[i].KeyTimeName[formLanguageIndex], "-", "-", "-");
            }
        }

        private void ResetBoxKeyTimeName()
        {
            grdTimeList.DefaultCellStyle.Font = keyTimeNameFont[formLanguageIndex];
            for (int i = 0; i < grdTimeList.Rows.Count; i++)
            {
                grdTimeList.Rows[i].Cells["colEquipName"].Value = NetLine.BoxKeyTime[i].KeyTimeName[formLanguageIndex];
            }
        }

        public void LoadBox()
        {
            //在lvKeyTime中进行数据的显示
            DateTime dt1, dt2;
            for (int i = 0; i < NetLine.BoxKeyTime.Count; i++)
            {
                dt1 = pbox.KeyTime[NetLine.BoxKeyTime[i].KeyTimeInIndex];
                dt2 = pbox.KeyTime[NetLine.BoxKeyTime[i].KeyTimeOutIndex];
                bool isok1 = !(dt1.Year < 2021);
                grdTimeList.Rows[i].Cells[2].Value = isok1 ? dt1.ToString("yyyy-MM-dd HH:mm:ss") : "-";
                bool isok2 = !(dt2.Year < 2021);
                grdTimeList.Rows[i].Cells[3].Value = isok2 ? dt2.ToString("yyyy-MM-dd HH:mm:ss") : "-";
                if (isok1 && isok2)
                {
                    TimeSpan ts = dt2.Subtract(dt1);
                    grdTimeList.Rows[i].Cells[4].Value = (new StringBuilder(ts.Hours.ToString()).Append(":").Append(ts.Minutes).Append(":").Append(ts.Seconds)).ToString();
                }
                else
                    grdTimeList.Rows[i].Cells[4].Value = "-";

            }
            lbl_BoxSerial.Text = pbox.BoxSerial.ToString();
            lbl_QuenchMoveinTime.Text = pbox.QuenchMoveinTime.ToString();
            lbl_ErrorCode.Text = pbox.ErrorCode.ToString();
            lbl_info.Text = pbox.OtherInfo.ToString();
            lbl_PostionIndex.Text = (pbox.PostionIndex + 1).ToString();
            lbl_Title.Text = (pbox.PostionIndex + 1).ToString();
            if (pbox.LoadIndex > 0)
                cmb_ColorSet.Enabled = txt_BoxSerial.Enabled = chk_ProcessBoxisLoad.Checked = true;
            else
                cmb_ColorSet.Enabled = txt_BoxSerial.Enabled = chk_ProcessBoxisLoad.Checked = false;
            txt_BoxSerial.Text = pbox.BoxSerial.ToString();
            cmb_ColorSet.SelectedIndex = pbox.LampCode;

        }

        public void StartModify()
        {
            if (fdUsers.UserRights == 4)
            {
                pnl_ProcessBoxInfoModify.Visible = true;
            }
            else
            {
                netForms.showLogin(6);
            }
        }
        private void judgeExistOrNot()
        {
            int _boxserial = 0;
            if (chk_ProcessBoxisLoad.Checked)//当设定为有料的情况下进行数据的判断
            {
                int.TryParse(txt_BoxSerial.Text.Trim(), out _boxserial);
                if (_boxserial == 0)
                {
                    fdMessage.ShowMsg(MultipleLanguage.messageInfos[14], "", formLanguageIndex);
                    //fdMessage.ShowMsg("请正确输入有料序号和料框编号！", "物料修改", 1, 0);
                    return;
                }
                if (_boxserial != pbox.BoxSerial)//料框编号修改了，需要对所有的料框编号进行检索，相同就不允许修改
                {
                    if (_boxserial > 999 || _boxserial < 1)
                    {
                        fdMessage.ShowMsg(MultipleLanguage.messageInfos[15], "", formLanguageIndex);
                        // fdMessage.ShowMsg("料框编号的输入范围为1~999，请重新输入！", "物料修改", 1, 0);
                        return;
                    }
                    for (int i = 0; i < NetLine.pBox.Count; i++)
                    {
                        if (NetLine.pBox[i].BoxSerial == _boxserial)
                        {
                            fdMessage.ShowMsg(MultipleLanguage.messageInfos[16], "", formLanguageIndex);
                            // fdMessage.ShowMsg("料框编号已存在，请重新输入！", "物料修改", 1, 0);
                            return;
                        }
                    }
                }
            }
            bool isok = false;
            try
            {
                if (chk_ProcessBoxisLoad.Checked)
                {
                    isok = pbox.ChangeBoxInfo(1, _boxserial, cmb_ColorSet.SelectedIndex);
                    if (isok) pbox.LampCode = cmb_ColorSet.SelectedIndex;
                }
                else
                    isok = pbox.ChangeBoxInfo(0, 0, 0);
            }
            catch (Exception)
            {
                // throw;
            }
            if (isok)
                    fdMessage.ShowMsg(MultipleLanguage.messageInfos[17], "", formLanguageIndex);
            else
                    fdMessage.ShowMsg(MultipleLanguage.messageInfos[18], "", formLanguageIndex);
                    //fdMessage.ShowMsg(isok ? "物料信息修改成功！" : "物料信息修改失败！", "物料修改", 1, 0);
            pnl_ProcessBoxInfoModify.Visible = false;
        }

        private void btn_ProcessBoxInfoModify_Click(object sender, EventArgs e)
        {
            StartModify();

        }
        private void btn_ModifyConfim_Click(object sender, EventArgs e)
        {
            judgeExistOrNot();
        }
        private void btn_ModifyCancel_Click(object sender, EventArgs e)
        {
            pnl_ProcessBoxInfoModify.Visible = false;
        }

        private void chk_ProcessBoxisLoad_CheckedChanged(object sender, EventArgs e)
        {
            cmb_ColorSet.Enabled = txt_BoxSerial.Enabled = chk_ProcessBoxisLoad.Checked;
            if (!chk_ProcessBoxisLoad.Checked) cmb_ColorSet.SelectedIndex = 0;
        }

        private void txt_BoxSerial_KeyPress(object sender, KeyPressEventArgs e)
        {
            fdPublicFunction.CheckInput(0, txt_BoxSerial.Text, e);
        }

        private void txt_BoxSerial_Leave(object sender, EventArgs e)
        {
            txt_BoxSerial.Text = txt_BoxSerial.Text.Trim();
            if (txt_BoxSerial.Text == "")
            {
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[19], "", formLanguageIndex);
                // fdMessage.ShowMsg("物料编号不能为空，请重新输入！", "物料修改", 1, 0);
                return;
            }
            try
            {
                if (Convert.ToInt32(txt_BoxSerial.Text) < 1) txt_BoxSerial.Text = "1";
                if (Convert.ToInt32(txt_BoxSerial.Text) > 999) txt_BoxSerial.Text = "999";
            }
            catch (Exception)
            {
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[20], "", formLanguageIndex);
                // fdMessage.ShowMsg("物料编号输入有误，请重新输入！", "物料修改", 1, 0);
            }
        }
        //private void ProcessBoxStatus()
        //{
        //    OperateResult<byte[]> res = NetLine.hslServer.SiemensPLC.Read(pbox._DBIndex + ".0", 1);
        //    if (!res.IsSuccess) return;
        //    bool[] x;
        //    x = res.Content.ToBoolArray();
        //    if (x[0] == true)
        //    {
        //        btn_ProcessBoxCut.BringToFront();
        //        btn_ProcessBoxCut.Visible = true;

        //    }
        //    else if (NetLine.CutProcessBoxData.Count == 0)
        //        return;
        //    else
        //        btn_ProcessBoxPaste.Visible = true;

        //}
        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
            //netForms.fmpbox = null;
        }

        private void Form_ProcessBox_Activated(object sender, EventArgs e)
        {
            if (MultipleLanguage.systemLanguageIndex != formLanguageIndex)
            {
                loadCmb();
                ResetBoxKeyTimeName();
            }
        }
        //private void btn_ProcessBoxCut_Click(object sender, EventArgs e)
        //{
        //    OperateResult<byte[]> res = NetLine.hslServer.SiemensPLC.Read(pbox._DBIndex + ".0", 56);
        //    if (!res.IsSuccess) return;
        //    NetLine.CutProcessBoxData[pb] = res.Content;
        //    NetLine.BoxSerialAndBoxMark.Add(pbox.BoxSerial, pbox.BoxMark.ToString());
        //    lst_NeedPasted.Items.Add(new ListViewItem(new string[] { pbox.BoxSerial.ToString(), pbox.BoxMark.ToString() }));
        //    NetLine.hslServer.SiemensPLC.Write(pbox._DBIndex + ".0", 0);
        //    this.Close();
        //}
        //private void btn_ProcessBoxPaste_Click(object sender, EventArgs e)
        //{
        //    switch (NetLine.CutProcessBoxData.Count)
        //    {
        //        case 1://仅仅有一个被剪切的数据，直接粘贴
        //            foreach (var item in NetLine.CutProcessBoxData.Keys)
        //            {
        //                PasteProcessBoxData(item);
        //            }
        //            NetLine.BoxSerialAndBoxMark.Clear();
        //            NetLine.CutProcessBoxData.Clear();
        //            this.Close();
        //            return;
        //        case 0://被剪切的数据列表欧中没有数据，直接返回
        //            this.Close();
        //            return;
        //    default:
        //        int _boxserial = 100;
        //        DateTime _boxmark = new DateTime(2023, 1, 1, 1, 11, 1);
        //        pnl_NeedPasted.Visible = true;
        //        _boxserial = pro.BoxSerial;
        //        _boxmark = pro.BoxMark;
        //        展示一个panle，显示被剪切的数据列表，选择后，进行数据查找并粘贴
        //        查找对应的
        //        ProcessBox pbox = lst_NeedPasted.Tag as ProcessBox;

        //        processbox pbox = ....tag as processbox
        //        ProcessBox pbox = NetLine.CutProcessBoxData.Keys.ToList().Find(x => x.BoxMark == _boxmark && x.BoxSerial == _boxserial);

        //        if (pbox != null)
        //        {
        //            isok = PasteProcessBoxData(pbox);
        //            if (isok)
        //            {
        //                NetLine.CutProcessBoxData.Remove(pbox);
        //                pbox.FlashData();//读取PLC数据到PB
        //                LoadBox();//显示当前的数据
        //            }
        //        }
        //        break;

        //}

        //isok的时候
        //隐藏粘贴按钮，隐藏待选的 panel
        //}

    }
}
